package com.example.maxfinance;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.util.Xml;

class MyAsyncTask extends AsyncTask<String, Integer, Integer>{
	
	public static final int SEND_SUCCESS = 1;
	public static final int SEND_FAIL = -1;
	
	public static final int UPLOAD_SUCCESS = 2;
	public static final int UPLOAD_FAIL = -2;
	
	public static final String ACTION_SIGNUP = "signup";
	public static final String ACTION_FILE_UPLOAD = "upload";
	
    public Context parent;
    public ProgressDialog dlgLoading;


	public MyAsyncTask(Context _parent) {
		parent = _parent;
	}
	
	@Override
	protected Integer doInBackground(String... params) {
		// TODO Auto-generated method stub
		int n = SEND_SUCCESS;
		if (params[0] == ACTION_SIGNUP) {
			n = signup();
		}
		
		if (params[0] == ACTION_FILE_UPLOAD) {
			n = fileUpload(params[1], params[2], params[3]);
		}
		
		return n;
	}
	
	@Override
	protected void onPreExecute() {
		
		dlgLoading = new ProgressDialog(parent);
    	dlgLoading.setMessage("\tLoading...");
    	dlgLoading.setCanceledOnTouchOutside(false);
    	dlgLoading.setCancelable(false);
        dlgLoading.show();
	}

	protected void onPostExecute(Integer result){
		Log.e("HCW", "post_end");

		if (dlgLoading.isShowing()) {
			dlgLoading.dismiss();
		}

		if (result == SEND_SUCCESS) {
			SubmitActivity sbmActivity = (SubmitActivity) parent;
			sbmActivity.goCompletePage();
		}
		
		if (result == SEND_FAIL) {
			SubmitActivity sbmActivity = (SubmitActivity) parent; 
			sbmActivity.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
					" record in your mobile.\n Please try submit when having internet connection");
		}
		
		if (result == UPLOAD_FAIL) {
			CompleteActivity completeActivity = (CompleteActivity) parent;
			completeActivity.showGeneralAlert("Connection Failed!", "There is no internet conncection right now, the data you submitted will be" +
					" record in your mobile.\n Please try submit when having internet connection");
		}
		if (result == UPLOAD_SUCCESS) {
			CompleteActivity completeActivity = (CompleteActivity) parent;
			completeActivity.showGeneralAlert("Connection Failed!", "Your file has been uploaded.");
		}
		
//		parent.startActivity(new Intent(parent, CompleteActivity.class));
	}
	
	protected void onProgressUpdate(Integer... progress){
//		Toast.makeText(getApplicationContext(), "failed", Toast.LENGTH_LONG).show();
//    	dlgLoading.dismiss();
	}

	public Integer signup() {
		
		// Create a new HttpClient and Post Header
		HttpPost httppost = new HttpPost("http://www.fairfinance.co.nz/applicationTest/MorganDB/mobile_proc.php");
//		HttpPost httppost = new HttpPost("http://192.168.1.101/Morgan/mobile_proc.php");

		HttpResponse response = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    int k = SEND_FAIL;
	    try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            
            nameValuePairs.add(new BasicNameValuePair("action", "signup"));
            nameValuePairs.add(new BasicNameValuePair("app_LoanAmount", GlobalData.personalInfo.strLoanAmount));
            nameValuePairs.add(new BasicNameValuePair("app_Title1", GlobalData.personalInfo.strTitle1));
            nameValuePairs.add(new BasicNameValuePair("app_FirstName1", GlobalData.personalInfo.strFirstName1));
            nameValuePairs.add(new BasicNameValuePair("app_MiddleName1", GlobalData.personalInfo.strMiddleName1));
            nameValuePairs.add(new BasicNameValuePair("app_Surname1", GlobalData.personalInfo.strSurname1));
            nameValuePairs.add(new BasicNameValuePair("app_Residency", GlobalData.personalInfo.strResidency));
            nameValuePairs.add(new BasicNameValuePair("app_DateOfBirth1", GlobalData.personalInfo.strDOB));
            nameValuePairs.add(new BasicNameValuePair("app_DriversLicence1", GlobalData.personalInfo.strDriversLicense1));
            nameValuePairs.add(new BasicNameValuePair("app_Mobile1", GlobalData.personalInfo.strMobilePhone1));
            nameValuePairs.add(new BasicNameValuePair("app_Phone1", GlobalData.personalInfo.strHomePhone1));
            nameValuePairs.add(new BasicNameValuePair("app_EMailAddress1", GlobalData.personalInfo.strEMailAddress));
            nameValuePairs.add(new BasicNameValuePair("app_ResidentialStatus1", GlobalData.personalInfo.strResidentialStatus));
            
            nameValuePairs.add(new BasicNameValuePair("app_ResidentialAddress1", GlobalData.personalInfo.strResidentialAddress1));
            nameValuePairs.add(new BasicNameValuePair("app_Suburb1", GlobalData.personalInfo.strSuburb1));
            nameValuePairs.add(new BasicNameValuePair("app_State1", GlobalData.personalInfo.strState1));
            nameValuePairs.add(new BasicNameValuePair("app_Postcode1", GlobalData.personalInfo.strPostcode1));
        	
            nameValuePairs.add(new BasicNameValuePair("app_NumberofDependant1", GlobalData.personalInfo.strNumberOfDependant1));
            nameValuePairs.add(new BasicNameValuePair("app_PurposeOfLoan1", GlobalData.personalInfo.strPurposeOfLoan1));
            nameValuePairs.add(new BasicNameValuePair("app_OtherPurpose", GlobalData.personalInfo.strOtherPurpose));
            nameValuePairs.add(new BasicNameValuePair("app_PurposeSummary", GlobalData.personalInfo.strPurposeSummary));
        	
            // Vehicle 1
            nameValuePairs.add(new BasicNameValuePair("app_Vehicle1Value", GlobalData.personalInfo.strVehcieValue1));
            nameValuePairs.add(new BasicNameValuePair("app_Motor1Make", GlobalData.personalInfo.strMotorMake1));
            nameValuePairs.add(new BasicNameValuePair("app_Motor1Model", GlobalData.personalInfo.strMotorModel1));
            nameValuePairs.add(new BasicNameValuePair("app_Vehicle1Owner", GlobalData.personalInfo.strVehicleOwner1));
            nameValuePairs.add(new BasicNameValuePair("app_Motor1Finance", GlobalData.personalInfo.strMotorFinance1));
            nameValuePairs.add(new BasicNameValuePair("app_Motor1Year", GlobalData.personalInfo.strMotorYear1));
            
            // Vehicle 2
            nameValuePairs.add(new BasicNameValuePair("app_Vehicle2Value", GlobalData.personalInfo.strVehcieValue2));
            nameValuePairs.add(new BasicNameValuePair("app_Motor2Make", GlobalData.personalInfo.strMotorMake2));
            nameValuePairs.add(new BasicNameValuePair("app_Motor2Model", GlobalData.personalInfo.strMotorModel2));
            nameValuePairs.add(new BasicNameValuePair("app_Vehicle2Owner", GlobalData.personalInfo.strVehicleOwner2));
            nameValuePairs.add(new BasicNameValuePair("app_Motor2Finance", GlobalData.personalInfo.strMotorFinance2));
            nameValuePairs.add(new BasicNameValuePair("app_Motor2Year", GlobalData.personalInfo.strMotorYear2));
            
            // PropertyValue 1(Real Estate1) 
//            nameValuePairs.add(new BasicNameValuePair("app_Property1Value", GlobalData.personalInfo.strMarketValue1));
            nameValuePairs.add(new BasicNameValuePair("app_Property1Address", GlobalData.personalInfo.strPropertyAddress1));
            nameValuePairs.add(new BasicNameValuePair("app_morarr1", GlobalData.personalInfo.strMorarr1));
            nameValuePairs.add(new BasicNameValuePair("app_Property1Owner", GlobalData.personalInfo.strPropertyOwner1));

            // PropertyValue 2(Real Estate2)
//            nameValuePairs.add(new BasicNameValuePair("app_Property2Value", GlobalData.personalInfo.strMarketValue2));
            nameValuePairs.add(new BasicNameValuePair("app_Property2Address", GlobalData.personalInfo.strPropertyAddress2));
            nameValuePairs.add(new BasicNameValuePair("app_morarr2", GlobalData.personalInfo.strMorarr2));
            nameValuePairs.add(new BasicNameValuePair("app_Property2Owner", GlobalData.personalInfo.strPropertyOwner2));
        	
            // Liabilities
            nameValuePairs.add(new BasicNameValuePair("app_BoardingRentingFee", GlobalData.personalInfo.strBoardingRentingCost));
            nameValuePairs.add(new BasicNameValuePair("app_LivingExpensesPayment", GlobalData.personalInfo.strLivingExpensesPayment));
            
        	/////Mortgage1
            nameValuePairs.add(new BasicNameValuePair("app_Property1Debt1st", GlobalData.personalInfo.strOwingCreditLimit1));
            nameValuePairs.add(new BasicNameValuePair("app_MortgagePayment1", GlobalData.personalInfo.strMothlyPayment1));
            nameValuePairs.add(new BasicNameValuePair("app_Property1Bank", GlobalData.personalInfo.strLender1));
            
        	/////Mortgage2
            nameValuePairs.add(new BasicNameValuePair("app_Property2Debt1st", GlobalData.personalInfo.strOwingCreditLimit2));
            nameValuePairs.add(new BasicNameValuePair("app_MortgagePayment2", GlobalData.personalInfo.strMothlyPayment2));
            nameValuePairs.add(new BasicNameValuePair("app_Property2Bank", GlobalData.personalInfo.strLender2));
        	
            // Persoanl loan
            nameValuePairs.add(new BasicNameValuePair("app_PersonalLoanOwing", GlobalData.personalInfo.strPersonalLoanOwing));
            nameValuePairs.add(new BasicNameValuePair("app_PersonalLoanPayment", GlobalData.personalInfo.strPersonalLoanPayment));
            nameValuePairs.add(new BasicNameValuePair("app_PersonalLoanBank", GlobalData.personalInfo.strPersonalLoanLender));

            //// Vehicle 1 owing
            nameValuePairs.add(new BasicNameValuePair("app_v1Owing", GlobalData.personalInfo.strVehicleOwing1));
            nameValuePairs.add(new BasicNameValuePair("app_v1Payment", GlobalData.personalInfo.strVehiclePayment1));
            nameValuePairs.add(new BasicNameValuePair("app_v1Lender", GlobalData.personalInfo.strVehicleLender1));
            
            //// Vehicle 2 owing
            nameValuePairs.add(new BasicNameValuePair("app_v2Owing", GlobalData.personalInfo.strVehicleOwing2));
            nameValuePairs.add(new BasicNameValuePair("app_v2Payment", GlobalData.personalInfo.strVehiclePayment2));
            nameValuePairs.add(new BasicNameValuePair("app_v2Lender", GlobalData.personalInfo.strVehicleLender2));
            
            //Emplyment details
            nameValuePairs.add(new BasicNameValuePair("app_TypeOfEmployment1", GlobalData.personalInfo.strEmploymentStatus));
            nameValuePairs.add(new BasicNameValuePair("app_TOE1", GlobalData.personalInfo.strEmploymentType));
            nameValuePairs.add(new BasicNameValuePair("app_TitleInOccupation1", GlobalData.personalInfo.strTitleOccupation));
            nameValuePairs.add(new BasicNameValuePair("app_BusinessName1", GlobalData.personalInfo.strEmployerName));
            nameValuePairs.add(new BasicNameValuePair("app_WorkPhone1", GlobalData.personalInfo.strHrContactNumber1));
        	
            ////Income details
            nameValuePairs.add(new BasicNameValuePair("app_IncomeAfterTax1", GlobalData.personalInfo.strIncomeAfterTax));
            nameValuePairs.add(new BasicNameValuePair("app_IncomeAfterTax1Period", GlobalData.personalInfo.strIncomeAfterTaxPeriod));
            nameValuePairs.add(new BasicNameValuePair("app_CentrelinkIncome1", GlobalData.personalInfo.strCenterLinkCom));
            nameValuePairs.add(new BasicNameValuePair("app_OtherIncomeSpecify1", GlobalData.personalInfo.strOtherIncomeSpecify));
            nameValuePairs.add(new BasicNameValuePair("app_RentalIncome1", GlobalData.personalInfo.strRentalIncome));
            nameValuePairs.add(new BasicNameValuePair("app_OtherIncomePeriod1", GlobalData.personalInfo.strOtherIncomePeriod));

            //Other information and credit
            nameValuePairs.add(new BasicNameValuePair("app_NameOfPartner1", GlobalData.personalInfo.strNamePartner));
            nameValuePairs.add(new BasicNameValuePair("app_ContactNumber1", GlobalData.personalInfo.strContactNumber));
            nameValuePairs.add(new BasicNameValuePair("app_Hardship1", GlobalData.personalInfo.strHardShip1));
            nameValuePairs.add(new BasicNameValuePair("app_CreditHistory1", GlobalData.personalInfo.strCreditHistory));
            nameValuePairs.add(new BasicNameValuePair("app_totalOutstanding1", GlobalData.personalInfo.strTotalOutstanding));
            nameValuePairs.add(new BasicNameValuePair("app_DateOfDischarge1", GlobalData.personalInfo.strDischargedDate));
            nameValuePairs.add(new BasicNameValuePair("app_DefaultAfterDischarge1", GlobalData.personalInfo.strDefaultAfterDischage));
            nameValuePairs.add(new BasicNameValuePair("app_ExistingClient", GlobalData.personalInfo.strExistingClient));
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);
            String responseBody = EntityUtils.toString(response.getEntity());
            Log.e("HCW", responseBody);

            String str = xmlParse(responseBody, ACTION_SIGNUP);
            
            if (str.equals("success")) {
            	k = SEND_SUCCESS;
            }

	    } catch (Exception ex) {
            // TODO Auto-generated catch block
	    	Log.e("HCW", ex.toString());
        }
	    
	    return k;
	}
	
	public Integer fileUpload(String appID, String fileType, String fileName) {
		HttpPost postData = new HttpPost();
		HttpResponse response = null;
	    HttpClient httpclient = new DefaultHttpClient();
	    
		MultipartEntity reqEntity = new MultipartEntity();
	    int k = UPLOAD_FAIL;

		//Get the text file
		File sdcard = Environment.getExternalStorageDirectory();
		File InputFile = new File(sdcard, fileName);
		
		try {
			if(InputFile.exists()) {
				reqEntity.addPart("action", new StringBody("upload"));
				reqEntity.addPart("app_id", new StringBody(appID));
				reqEntity.addPart("photo_type", new StringBody(fileType));
				reqEntity.addPart("file_name", new StringBody(fileName));
				reqEntity.addPart("uploaded_file", new FileBody(InputFile));
				postData.setEntity(reqEntity);
			}
			
			postData.setURI(new URI("http://www.fairfinance.co.nz/applicationTest/MorganDB/mobile_proc.php"));
			response = httpclient.execute(postData);
			
          	String responseBody = EntityUtils.toString(response.getEntity());
            Log.e("HCW", responseBody);

            String str = xmlParse(responseBody, ACTION_FILE_UPLOAD);
            
            if (str.equals("success")) {
            	k = UPLOAD_SUCCESS;
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return k;
	}
	
	public String xmlParse(String result, String action) throws XmlPullParserException, IOException {
		
		XmlPullParser parser = Xml.newPullParser();
		String strResult = "fail";
		
	    try {
	    	parser.setInput(new StringReader(result));
	    } catch (XmlPullParserException e) {
	    	// 	TODO Auto-generated catch block
	    	e.printStackTrace();
	    }
	        
        int eventType = parser.getEventType();
 
        String xmlNodeName = null;
        while (eventType != XmlPullParser.END_DOCUMENT) {
        	
            switch (eventType) {
	             case XmlPullParser.START_TAG:
	                 xmlNodeName = parser.getName();
	                 break;
	             case XmlPullParser.TEXT:
	            	 if (xmlNodeName.equals("app_id")) {
	            		 GlobalData.personalInfo.strAppID = parser.getText();
	            		 
	            		 Log.e("HCW", GlobalData.personalInfo.strAppID);
	            	 }
	            	 if (xmlNodeName.equals(action)) {
	            		 strResult = parser.getText();
	            	 }
	            	 break;
            }
            
            eventType = parser.next();
        }
        
        return strResult;
	}
}
	
